﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SecTool.WinUI.Properties;

namespace SecTool.WinUI
{
    public partial class Login : Form
    {
        /// <summary>
        /// membership handler instance
        /// </summary>
        private Membership membership;

        public Login()
        {
            InitializeComponent();
            membership = Membership.Instance;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (membership.ValidateUser(tbUsername.Text, tbPassword.Text))
            {
                SecTool mainForm = new SecTool(tbUsername.Text);
                this.Hide();
                var result = mainForm.ShowDialog(this);
                if (result == System.Windows.Forms.DialogResult.Cancel)
                {
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show(Resources.InvalidPasswordMessage);
            }
        }

        private bool ValidateLogin()
        {
            if (string.IsNullOrEmpty(tbUsername.Text.Trim()) || string.IsNullOrEmpty(tbPassword.Text.Trim()))
            {
                //MessageBox.Show(Resources.EmptyUsernamePasswordMessage);
                return false;
            }
            return membership.UserExists(tbUsername.Text);
        }

        private bool ValidateRegister()
        {
            if (string.IsNullOrEmpty(tbUsername.Text.Trim()) || string.IsNullOrEmpty(tbPassword.Text.Trim()))
            {
                //MessageBox.Show(Resources.EmptyUsernamePasswordMessage);
                return false;
            }
            return !membership.UserExists(tbUsername.Text);
        }

        private void btnNewUser_Click(object sender, EventArgs e)
        {
            membership.AddUser(tbUsername.Text, tbPassword.Text);
            membership.SerializeToFile();
            Core.Crypto.KeyProvider.GetRSA(tbUsername.Text);
            UpdateButtonState();
        }

        private void tbUsername_Validating(object sender, CancelEventArgs e)
        {
            UpdateButtonState();
        }

        private void tbPassword_TextChanged(object sender, EventArgs e)
        {
            UpdateButtonState();
        }

        private void tbPassword_Validating(object sender, CancelEventArgs e)
        {
            UpdateButtonState();
        }

        private void UpdateButtonState()
        {
            btnLogin.Enabled = ValidateLogin();
            btnNewUser.Enabled = ValidateRegister();
        }
    }
}